<template>
  <div>
    <div class="user-info-head" @click="editCropper()"><img :src="options.img" class="img-circle"></div>
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @opened="modalOpened" @close="closeDialog()">
      <el-row>
        <el-col :span="12" class="tool-preview-left">
          <vue-cropper
            v-if="visible"
            ref="cropper"
            :img="options.img"
            :info="true"
            :auto-crop="options.autoCrop"
            :auto-crop-width="options.autoCropWidth"
            :auto-crop-height="options.autoCropHeight"
            :fixed-box="options.fixedBox"
            @realTime="realTime"
          />
        </el-col>
        <el-col :span="12" class="tool-preview-right">
          <div class="avatar-upload-preview">
            <img :src="previews.url" :style="previews.img">
          </div>
        </el-col>
      </el-row>
      <br>
      <el-row>
        <el-col :span="12" class="tool-left">
          <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
            <el-button size="small">选择<i class="el-icon-upload el-icon--right" /></el-button>
          </el-upload>
          <el-button icon="el-icon-plus" size="small" @click="changeScale(1)" />
          <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)" />
          <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()" />
          <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()" />
        </el-col>
        <el-col :span="12" class="tool-right">
          <el-button type="primary" size="small" @click="uploadImg()">上传</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import store from '@/store'
import { VueCropper } from 'vue-cropper'
import { upload } from '@/api/cloudStorage'

export default {
  name: 'Avatar',
  components: { VueCropper },
  props: {},
  data() {
    return {
      open: false, // 是否显示弹出层
      visible: false, // 是否显示cropper
      title: '上传头像', // 弹出层标题
      options: {
        img: store.getters.avatar, // 裁剪图片的地址
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 200, // 默认生成截图框宽度
        autoCropHeight: 200, // 默认生成截图框高度
        fixedBox: true // 固定截图框大小不允许改变
      },
      previews: {},
      originalFileName: 'blob', // 默认上传文件名称
      originalFileType: '', // 默认上传文件类型
      originalFileSize: 0 // 默认上传文件大小（MB）
    }
  },
  methods: {
    // 编辑头像
    editCropper() {
      this.open = true
      // 每次打开将图片转为base64，以解决OSS跨域问题
      this.setAvatarBase64(store.getters.avatar, (base64) => {
        this.options.img = base64
      })
    },
    // 将用户头像转换为base64格式
    setAvatarBase64(src, callback) {
      const _this = this
      const image = new Image()
      image.src = src + '?v=' + Math.random()
      image.crossOrigin = '*'
      image.onload = function() {
        const base64 = _this.transBase64FromImage(image)
        callback && callback(base64)
      }
    },
    // 将网络图片转换成base64格式
    transBase64FromImage(image) {
      const canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height
      const ctx = canvas.getContext('2d')
      ctx.drawImage(image, 0, 0, image.width, image.height)
      return canvas.toDataURL('image/png')
    },
    // 打开弹出层结束时的回调
    modalOpened() {
      this.visible = true
    },
    // 覆盖默认的上传行为
    requestUpload() {
    },
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft()
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight()
    },
    // 图片缩放
    changeScale(num) {
      num = num || 1
      this.$refs.cropper.changeScale(num)
    },
    // 上传预处理
    beforeUpload(file) {
      this.originalFileName = file.name
      this.originalFileType = file.type
      this.originalFileSize = file.size / 1024 / 1024
      if (this.originalFileType.indexOf('image/') === -1) {
        this.$notify.error({ title: '系统提示', message: '请上传图片类型！' })
      } else if (this.originalFileSize >= 2) {
        this.$notify.error({ title: '系统提示', message: '图片大小超限制，默认上限2MB！' })
      } else {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.options.img = reader.result
        }
      }
    },
    // 上传图片
    uploadImg() {
      this.$refs.cropper.getCropBlob(data => {
        const formData = new FormData()
        const fileOfBlob = new File([data], this.originalFileName)
        formData.append('file', fileOfBlob)
        upload(formData).then(response => {
          if (response.code === 200) {
            this.open = false
            this.options.img = response.url
            store.commit('user/SET_AVATAR', this.options.img)
            this.$notify.success({ title: '系统提示', message: response.msg })
            this.visible = false
          }
        })
      })
    },
    // 实时预览
    realTime(data) {
      this.previews = data
    },
    // 关闭窗口
    closeDialog() {
      this.options.img = store.getters.avatar
      this.visible = false
    }
  }
}
</script>
<style scoped lang="scss">
.user-info-head {
  width: 80px;
  height: 80px;
  position: relative;
  display: inline-block;
  display: flex;
  text-align: center;
  justify-items: center;

  img-circle {
    width: 80px;
    height: 80px;
    border-radius: 50%;
  }

  img {
    border-radius: 10px;
  }
}

.user-info-head:hover:after {
  content: '+';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  color: #eee;
  background: rgba(0, 0, 0, 0.5);
  font-size: 24px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  cursor: pointer;
  line-height: 80px;
  border-radius: 50%;
}

.avatar-upload-preview {
  width: 200px;
  height: 200px;
  overflow: hidden;
  position: relative;
  top: 50%;
  border-radius: 50%;
  -webkit-transform: translate(50%,-50%);
  transform: translate(50%,-50%);
  -webkit-box-shadow: 0 0 4px #ccc;
  box-shadow: 0 0 4px #ccc;
}

.tool-preview-left, .tool-preview-right {
  height: 350px;
  border: 1px solid #F0F0F0;
}

.tool-left {
  display: flex;
}

.tool-right {
  display: flex;
  justify-content: center;
}

.el-dialog__wrapper {
  ::v-deep .el-dialog {
    border-top-left-radius: 7px;
    border-top-right-radius: 7px;
    .el-dialog__header {
      border-top-left-radius: 7px;
      border-top-right-radius: 7px;
      background-color: #1890ff;
      padding: 14px;
      .el-dialog__title {
        color: #fff;
        font-size: 16px;
        font-weight: 600;
      }
      .el-dialog__close {
        color: #fff;
      }
    }
    .el-dialog__body {
      padding: 20px;
      .tool-left {
        .el-button {
          margin-left: 20px !important;
        }
        .el-button:first-child {
          margin-left: 0px !important;
        }
      }
      .tool-right {
        .el-button {
          margin-left: 25px !important;
        }
      }
    }
  }
}
</style>
